﻿using UnityEngine;
using System;
using System.IO;
using ProtoBuf;
using mProtos.Role;

public class mTestOperator1 : MonoBehaviour
{
    SelfNetwork net = new SelfNetwork();
    
    void Start()
    {
        net.LinkGame("127.0.0.1", 34530);
    }

    void OnGUI()
    {
        if (GUILayout.Button("Test", GUILayout.Width(200f), GUILayout.Height(200f)))
        {
            ///head
            byte[] head = new byte[5];
            //byte HEAD_0 = 0;
            head[0] = 0;
            //byte HEAD_1 = 0;
            head[1] = 0;
            //byte HEAD_2 = 0;
            head[2] = 0;
            //byte HEAD_3 = 0;
            head[3] = 0;
            //byte ProtoVersion = 0;
            head[4] = 0;

            byte[] ServerVersion = System.BitConverter.GetBytes(0);

            ///body
            CreatePlayerRequest request = new CreatePlayerRequest();
            request.name = "zhangsan";
            request.password = "123";
            byte[] body = Serialize(request);
           

            byte[] length = System.BitConverter.GetBytes(body.Length + 4);
            System.Array.Reverse(length);

            ///commandId = 1
            byte[] commandId = System.BitConverter.GetBytes(1);
            System.Array.Reverse(commandId);

            byte[] allBytes = new byte[head.Length + ServerVersion.Length + length.Length + commandId.Length + body.Length];

            int nowlength = 0;

            System.Array.Copy(head, 0, allBytes, nowlength, head.Length);
            nowlength = head.Length;
            
            System.Array.Copy(ServerVersion, 0, allBytes, nowlength, ServerVersion.Length);
            nowlength += ServerVersion.Length;

            System.Array.Copy(length, 0, allBytes, nowlength, length.Length);
            nowlength += length.Length;

            System.Array.Copy(commandId, 0, allBytes, nowlength, commandId.Length);
            nowlength += commandId.Length;

            //print("nowlength" + nowlength);

            System.Array.Copy(body, 0, allBytes, nowlength, body.Length);

            print("allBytes.Length" + allBytes.Length);

            net.SendData(allBytes);
        }
    }

    public static byte[] Serialize(IExtensible msg)
    {
        byte[] result;
        using (var stream = new MemoryStream())
        {
            Serializer.Serialize(stream, msg);
            result = stream.ToArray();
        }
        return result;
    }

    public static IExtensible Deserialize<IExtensible>(byte[] message)
    {
        IExtensible result;
        using (var stream = new MemoryStream(message))
        {
            result = Serializer.Deserialize<IExtensible>(stream);
        }
        return result;
    }
}
